package com.obrempon.credit.market.ui.activity

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.obrempon.credit.market.ObremponApp
import com.obrempon.credit.market.databinding.ObremponCameraSelfieActBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpAct
import com.obrempon.credit.market.httptest.api.UpdateImageApi
import com.obrempon.credit.market.request.HttpHelper
import com.obrempon.credit.market.utils.ObremponImageUtil
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.imgcovert.ImageConvert
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.module.easyhttp.config.IRequestApi
import com.obrempon.module.easyhttp.listener.OnUpdateListener
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 17:12
 * @Annotation：自拍照
 */
class ObremponCameraSelfieAct: HttpAct() {
    lateinit var binding: ObremponCameraSelfieActBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""


    override fun takeObremponRootView(): View {
        binding = ObremponCameraSelfieActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        ObremponTitleBarUtil.setStatusBarLightMode(this, false)
        binding.selfieTitleLayout.setPadding(0, ObremponTitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCameraSelfie()
    }

    override fun initObremponListener() {
        binding.selfieImgBack.setOnClickListener {
            finish()
        }
        binding.selfieImgCustomer.setOnClickListener {
            val eventTitle = "SelfieCamera Page"
            showCustomerDialog(eventTitle)
            doEventTrackAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,eventTitle)
        }
        //拍照
        binding.imgCameraTakePictures.setOnClickListener {
            doEventTrackAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CAMERA_TAKE_PHOTO,"SelfieCamera Page")
            takeCameraSelfieFilePhoto()
        }

        //重拍
        binding.selfieCameraRemakeLayout.setOnClickListener {
            doEventTrackAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_SELFIE_REMAKE,"SelfieCamera Page")
            showCameraFaceTakeView()
        }

        //使用
        binding.selfieCameraUsePhotoLayout.setOnClickListener {
            doEventTrackAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_SELFIE_USE_PHOTO, imgUsePath)
            showObremponLoading()
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    ObremponLogger.e("imageConvert success>>>>>>>$localPath")
                    uploadObremponImageAction(localPath)
                }
            }
        }
    }

    override fun takeObremponData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCameraSelfie() {
        showCameraFaceTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.selfieCameraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraSelfieFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = ObremponApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture!!.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    ObremponLogger.e("take photo complete>>>>>>>${imgUri!!.path}")
                    imgUsePath = imgUri!!.path!!
                    ObremponImageUtil.instance.loadImageUrl(this@ObremponCameraSelfieAct,binding.selfiePreview,imgUsePath,0)
                    showCameraFaceCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    ObremponLogger.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraFaceTakeView(){
        binding.selfiePreview.visibility = View.GONE
        binding.imgCameraTakePictures.visibility = View.VISIBLE
        binding.selfieCameraRemakeLayout.visibility = View.GONE
        binding.selfieCameraUsePhotoLayout.visibility = View.GONE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraFaceCompleteView(){
        binding.selfiePreview.visibility = View.VISIBLE
        binding.imgCameraTakePictures.visibility = View.GONE
        binding.selfieCameraRemakeLayout.visibility = View.VISIBLE
        binding.selfieCameraUsePhotoLayout.visibility = View.VISIBLE
    }

    /**
     * 图片上传完成
     */
    fun showObremponUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 图片上传
     */
    private fun uploadObremponImageAction(imgPath: String){
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : OnUpdateListener<UpdateImageApi.ImageBean> {
            override fun onUpdateProgressChange(progress: Int) {
                ObremponLogger.e(">onUpdateProgressChange>>>>>>>>>>>>>>>>$progress")
            }

            override fun onUpdateFail(throwable: Throwable) {
                ObremponLogger.e(">throwable>>>>>>>>>>>>>>>>")
            }

            override fun onUpdateSuccess(result: UpdateImageApi.ImageBean) {
                ObremponLogger.e(">onUpdateSuccess>>>>>>>>>>>>>>>>${result.obj.url}")
                when(result.code){
                    0 -> {
                        val imgUrl = result.obj.url
                        showObremponUploadImageSuccess(imgPath,imgUrl)
                    }
                    else -> {
                        showObremponToast(result.msg)
                    }
                }
            }

            override fun onUpdateEnd(api: IRequestApi) {
                ObremponLogger.e(">onUpdateEnd>>>>>>>>>>>>>>>>")
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        doEventTrackAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_SELFIE_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        doEventTrackAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_SELFIE_CAMERA_END)
        cameraExecutor.shutdown()
    }
}